package com.itheima.Arrays.二分查找;

/**
 * @Author 王加鑫
 * @Date 2021/5/10 16:16
 * @Version 1.0
 * 二分查找
 */
public class Demo1 {
    public static void main(String[] args) {
        int[] arr = {11,22,33,44,55,66};
        //要查找的数
        int num = 22;
        //二分查找方法（排好序的数组，指定查找数据）查到了返回查找数据的索引，没查到返回-1
        int index = binarySearchForIndex(arr,num);
        System.out.println(index);
    }

    private static int binarySearchForIndex(int[] arr, int num) {
        //定义查找范围
        int min = 0;
        int max = arr.length-1;
        while (min <= max){
            int mid = (min + max) >>1;
            //如果中间索引值比num小，那么缩小范围，最小值为mid的索引+1
            if(arr[mid] < num){
                min = mid + 1;
            }else if(arr[mid] > num){
                //如果中间索引值比num大，那么缩小范围，最大值为mid的索引-1
                max = mid - 1;
            }else {
                //min = max说明找到了返回该索引
                return mid;
            }
        }
        //说明没有找到num
        return -1;
    }
}
